import { Component, View, ElementRef, OnInit } from 'angular2/angular2';
import { Router, RouterLink } from 'angular2/router';

import { status, json } from '/resources/ts/fetch.ts';

declare var $: any;

@Component({
  selector: 'login-box'
  templateUrl: '/resources/template/login.html',
  directives: [RouterLink]
})
export class Login implements OnInit {

  elementRef: ElementRef;

  // email: string;
  // password: string;
  //
  // constructor( elementRef: ElementRef) {
  //
  //   this.elementRef = elementRef;
  //
  //   this.email = 'xxx@xxx.com';
  //   this.password = 'password';
  // }

  constructor(public router: Router, elementRef: ElementRef) {
    this.elementRef = elementRef;

    document.getElementsByTagName('body')[0].className = 'hold-transition login-page';
  }

  onInit() {
    $(this.elementRef.nativeElement).find('#ng-checkbox__remember-me').iCheck({
      checkboxClass: 'icheckbox_square-blue',
      radioClass: 'iradio_square-blue',
      increaseArea: '20%' // optional
    });
  }

  login(event, username, password) {
    event.preventDefault();

    var form = document.querySelector('.login-box form');
    console.log(form);

    window.fetch('/login', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        //'Content-Type': 'application/x-www-form-urlencoded'
        'Content-Type': 'application/json'
      },
      //body: new FormData(form)
      body: JSON.stringify({
        username, password
      })
      // body: {
      //   'username': username,
      //   'password': password
      // })
    })
      .then(status)
      .then(json)
      .then((response: any) => {
      localStorage.setItem('jwt', response.id_token);
      this.router.parent.navigateByUrl('/');
    })
      .catch((error) => {
      alert(error.message);
      console.log(error.message);
    });
  }
}
